package top.fangw.tenant.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.ItemDataSource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.fangw.common.api.vo.TenantInfoVo;
import top.fangw.common.core.result.Result;
import top.fangw.common.log.annotation.Log;
import top.fangw.tenant.pojo.dto.TenantInfoQueryDto;
import top.fangw.tenant.pojo.entity.TenantInfo;
import top.fangw.tenant.service.ITenantInfoService;

import javax.sql.DataSource;
import java.util.Map;

/**
 * <p>
 * 用途：用于管理系统中的租户信息 前端控制器
 * </p>
 *
 * @author fangw
 * @since 2024-01-16
 */
@Tag(name = "租户信息管理")
@RestController
@RequestMapping("/tenant-info")
@RequiredArgsConstructor
public class TenantInfoController {

    private final ITenantInfoService tenantInfoService;

    private final DataSource dataSource;

    @Log
    @Operation(summary ="添加租户信息")
    @PostMapping("/add")
    public Result<?> add(@RequestBody TenantInfo tenantInfo) {
       tenantInfoService.add(tenantInfo);
        return Result.success();
    }

    @Log
    @Operation(summary ="查询多数据源信息")
    @GetMapping("/datasource")
    public Result<?> datasource() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        Map<String, DataSource> dataSources = ds.getDataSources();
        dataSources.forEach((k,v)->{
            DruidDataSource druidDataSource = null;
            if(v instanceof ItemDataSource item){
                DataSource dataSource1 = item.getDataSource();
                druidDataSource = (DruidDataSource) dataSource1;
            }else{
                druidDataSource = (DruidDataSource) v;
            }
        });
//        tenantInfoService.add(tenantInfo);
        return Result.success(dataSources.toString());
    }

    @Log
    @Operation(summary ="根据租户id查询租户信息")
    @GetMapping("/getByTenantId")
    public Result<?> getByTenantId(@RequestParam String tenantId) {
        TenantInfo res = tenantInfoService.getByTenantId(tenantId);
        return Result.success(res);
    }

    @Log
    @Operation(summary ="根据租户id查询租户信息")
    @GetMapping("/getByTenantIdFeign")
    public Result<TenantInfoVo> getByTenantIdFeign(@RequestParam String tenantId) {
        TenantInfo res = tenantInfoService.getByTenantId(tenantId);
        TenantInfoVo tenantInfoVo = BeanUtil.copyProperties(res, TenantInfoVo.class);
        return Result.success(tenantInfoVo);
    }


    @Log
    @Operation(summary ="分页查询租户信息")
    @PostMapping("/pageList")
    public Result<?> pageList(@RequestBody TenantInfoQueryDto queryDto) {
        IPage<TenantInfo> res  = tenantInfoService.pageList(queryDto);
        return Result.success(res);
    }


}
